package com.file.parser;


import com.file.bo.AppGjzwfwYlbx;
import com.file.bo.ResponseData;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class AppGjzwfwYlbxXmlParser {

    public ResponseData<String> parseAppGjzwfwYlbxXmlToJson(String daId, String filePath) {
        log.info("parseAppGjzwfwYlbxXmlToJson started, daId:{}, filePath:{}", daId, filePath);
        String json = null;

        try {
            if (filePath.contains("_ylbx.xml")) {
                AppGjzwfwYlbx.YlbxQueryResult ylbxQueryResult = parseAppGjzwfwYlbxQueryResultXml(filePath);
                json = JsonUtils.convertObjectToJson(ylbxQueryResult);
            } else if (filePath.contains("_sbk.xml")) {
                AppGjzwfwYlbx.SbkInfo ylbxSbkInfo = parseAppGjzwfwYlbxSbkInfoXml(filePath);
                json = JsonUtils.convertObjectToJson(ylbxSbkInfo);
            }

        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseAppGjzwfwYlbxXmlToJson failed", e);
            return new ResponseData<>(json, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseAppGjzwfwYlbxXmlToJson completed, daId:{}, filePath:{}, json:{}", daId, filePath, json);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private AppGjzwfwYlbx.YlbxQueryResult parseAppGjzwfwYlbxQueryResultXml(String filePath) throws Exception {
        AppGjzwfwYlbx.YlbxQueryResult ylbxQueryResult = new AppGjzwfwYlbx.YlbxQueryResult();
        List<AppGjzwfwYlbx.Ylbx> ylbxList = new ArrayList<>();
        ylbxQueryResult.setYlbxList(ylbxList);
        AppGjzwfwYlbx.Ylbx ylbx = null;

        List<String> nodeTextList = getNodeTextList(filePath);
//        System.out.println(nodeTextList);

        String sectionName = "";

        for( String nodeText : nodeTextList) {
            if (StringUtils.equals(nodeText, "对应费款所属期")) {
                sectionName = "对应费款所属期";
                continue;
            } else if (StringUtils.equals(nodeText, "参保地名称")) {
                sectionName = "参保地名称";
                continue;
            } else if (StringUtils.equals(nodeText, "单位名称")) {
                sectionName = "单位名称";
                continue;
            } else if (StringUtils.equals(nodeText, "个人缴费金额（元）")) {
                sectionName = "个人缴费金额";
                continue;
            } else if (nodeText.contains("如对查询结果有疑问")) {
                break;
            }

            switch (sectionName) { //NOSONAR
                case "对应费款所属期":
                    ylbx = new AppGjzwfwYlbx.Ylbx();
                    ylbx.setPeriod(nodeText);
                    break;
                case "参保地名称":
                    ylbx.setInsuranceLocationName(nodeText);
                    break;
                case "单位名称":
                    ylbx.setCompanyName(nodeText);
                    break;
                case "个人缴费金额":
                    ylbx.setPersonalPaymentAmount(nodeText);
                    ylbxList.add(ylbx);
                    break;
            }

        }

        return ylbxQueryResult;
    }

    private AppGjzwfwYlbx.SbkInfo parseAppGjzwfwYlbxSbkInfoXml(String filePath) throws Exception {
        AppGjzwfwYlbx.SbkInfo ylbxSbkInfo = new AppGjzwfwYlbx.SbkInfo();
        List<AppGjzwfwYlbx.Sbk> sbkList = new ArrayList<>();
        ylbxSbkInfo.setSbkList(sbkList);

        AppGjzwfwYlbx.Sbk sbk = null;

        List<String> nodeTextList = getNodeTextList(filePath);
//        System.out.println(nodeTextList);
        String sectionName = "";
        for (String nodeText : nodeTextList) {
            if (nodeText.equals("我的社保卡")) {
                sectionName = "我的社保卡";
                continue;
            } else if (nodeText.equals("社会保障号码")) {
                sectionName = "社会保障号码";
                continue;
            } else if (nodeText.startsWith("参保地")) {
                sectionName = "参保地";
            } else if (nodeText.equals("切换参保地")) {
                continue;
            } else if (nodeText.startsWith("社会保障卡号")) {
                sectionName = "社会保障卡号";
                continue;
            } else if (nodeText.startsWith("社保卡银行账户发卡行")) {
                sectionName = "社保卡银行账户发卡行";
                continue;
            } else if (nodeText.startsWith("社保卡银行账户")) {
                sectionName = "社保卡银行账户";
                continue;
            } else if (nodeText.startsWith("社会保障卡应用状态")) {
                sectionName = "社会保障卡应用状态";
                continue;
            } else if (nodeText.startsWith("发卡地")) {
                sectionName = "发卡地";
                continue;
            } else if (nodeText.contains("如果您在省内多个地市参保过")) {
                break;
            }

            switch (sectionName) { //NOSONAR
                case "我的社保卡":
                    ylbxSbkInfo.setName(nodeText);
                    break;
                case "社会保障号码":
                    ylbxSbkInfo.setSocialSecurityNumber(nodeText);
                    break;
                case "参保地":
                    sbk = new AppGjzwfwYlbx.Sbk();
                    sbk.setInsuranceLocation(nodeText.substring(3));
                    break;
                case "社会保障卡号":
                    sbk.setSocialSecurityCardNumber(nodeText);
                    break;
                case "社会保障卡应用状态":
                    sbk.setSocialSecurityCardAppStatus(nodeText);
                    break;
                case "发卡地":
                    sbk.setCardIssueLocation(nodeText);
                    sbkList.add(sbk);
                    break;
            }
        }

        return ylbxSbkInfo;
    }

    public List<String> getNodeTextList(String filePath) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(filePath));

        return parseNode(document.getRootElement().elements());
    }

    private List<String> parseNode(List<Element> elements) {
        List<String> nodeTextList = new ArrayList<>();
        elements.forEach(element -> {
            String text = element.attributeValue("text");
            if (StringUtils.isNotBlank(text)) {
                nodeTextList.add(text);
            }
            nodeTextList.addAll(parseNode(element.elements()));
        });

        return nodeTextList;
    }

    public static void main(String[] args) throws Exception {
        AppGjzwfwYlbxXmlParser appGjzwfwYlbxXmlParser = new AppGjzwfwYlbxXmlParser();
        String json = appGjzwfwYlbxXmlParser.parseAppGjzwfwYlbxXmlToJson("daid", "D:\\data\\file\\app-gjzwfw-ylbx\\app-gjzwfw-ylbx_sbk.xml").getData();
        System.out.println(json);
    }

}
